<template>
  <el-dialog class="public-dialog" title="添加商品" width="90vw" :modelValue="modelValue" @close="handleClose" draggable align-center :close-on-click-modal="false">
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="form" :originOption="originOption" />
      </template>

      <!-- 关联副店铺 -->
      <template #SubStoreName="{ row }">
        <template v-for="(item, i) in row.base_asin_store" :key="i">
          <VText :value="item.sub_store_name" :line="1" v-if="i < 2" />
        </template>
        <el-popover placement="left" :width="200" trigger="click" v-if="row.base_asin_store.length > 2">
          <div>
            <VText v-for="(item, i) in row.base_asin_store" :key="i" :value="item.sub_store_name" :line="1" />
          </div>
          <template #reference>
            <el-link type="primary" :underline="false">查看更多</el-link>
          </template>
        </el-popover>
      </template>
    </VTable>

    <template #footer>
      <el-button @click="handleClose"> 取消 </el-button>
      <el-button type="primary" :loading="loading" @click="submit"> 确认 </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from "element-plus"
import { asinManagementList } from "@/api/base"
import XForm from "@/components/XForm/index.vue"
const emit = defineEmits(["submit", "handleClose"])

const props = defineProps({
  handleType: { type: String, default: "" }, // 操作类型
})

const modelValue = ref(false)
const data = reactive({
  loading: false,
})
const { loading } = toRefs(data)
const tableRef = ref()
const tableOptions = reactive({
  formConfig: {
    data: {
      userRange: { type: "operator_user", value: null },
    },
  },
  height: 600,
  columns: [
    { field: "activity_status_text", title: "活跃状态", width: 80 },
    { field: "site_code", title: "国家", width: 100 },
    { field: "store_name", title: "ASIN店铺", width: 160 },
    { field: "asin", title: "ASIN", width: 120 },
    {
      field: "status_text",
      title: "SKU/自定义SKU",
      width: 150,
      slots: {
        default: ({ row }) => (
          <div>
            <VText value={row.sku} line={1} />
            <VText value={row.custom_sku} line={1} />
          </div>
        ),
      },
    },
    { field: "main_store_name", title: "主店铺", width: 150 },
    {
      field: "sub_store_name",
      title: "关联副店铺",
      width: 180,
      // slots: { default: "SubStoreName" },
    },

    {
      field: "sku_title",
      title: "商品名称",
      width: 260,
      slots: {
        default: ({ row }) => <VText value={row.sku_title} line={2} />,
      },
    },
    {
      title: "状态",
      field: "status_text",
      width: 100,
      slots: {
        default: ({ row }) => <VStatus value={row.status_text == "启用"} />,
      },
    },
    { field: "operator_user_text", title: "运营人员", width: 120 },
    { field: "department_name", title: "部门", width: 200 },
  ],

  proxyConfig: {
    autoLoad: false, // 是否自动加载查询数据
    ajax: {
      query: async ({ page, form }) => {
        let params = {
          ...initForm(form),
          page: page.pageNum,
          page_size: page.pageSize,
        }
        let res = await asinManagementList(params)
        res.data = res.data.filter((v) => v.id != formData.value?.base_asin_list?.id)
        return res
      },
    },
  },
})

const originOption = ref({})
const formOption = ref({})
const fieldList = ref([
  {
    field: "activity_status",
    type: "select",
    originField: "Base.BaseAsinList.ActivityStatusEnum",
    options: { placeholder: "活跃度" },
    style: { width: "120px" },
  },
  {
    field: "site_code",
    type: "select",
    originField: "amazonSite",
    multiple: true,
    collapseTags: true,
    options: { placeholder: "国家" },
    style: { width: "200px" },
  },
  { field: "sku", placeholder: "SKU", type: "textarea", style: { width: "200px" } },
  { field: "custom_sku", placeholder: "自定SKU", type: "textarea", style: { width: "200px" } },
  { field: "asin", placeholder: "ASIN", type: "textarea", style: { width: "200px" } },
  {
    field: "userRange",
    type: "cascaderNew",
    selectStyle: { width: "140px" },
    select: [
      { label: "运营人员", value: "operator_user" },
      { label: "计划人员", value: "planner_user" },
      { label: "添加人员", value: "created_by" },
    ],
    style: { width: "200px" },
  },
  {
    field: "status",
    type: "select",
    originField: "Base.BaseAsinList.StatusEnum",
    options: { placeholder: "状态" },
    style: { width: "120px" },
  },
])
const submit = () => {
  let checkboxRecords = []
  if (props.handleType == "asin") {
    checkboxRecords = tableRef.value.$table.getRadioRecord()
    checkboxRecords = checkboxRecords ? [checkboxRecords] : []
  } else {
    checkboxRecords = tableRef.value.$table.getCheckboxRecords()
  }
  if (!checkboxRecords.length) {
    return ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
  }
  emit("submit", checkboxRecords)
  handleClose()
}
const handleClose = () => {
  modelValue.value = false
}

import { getEnum, getAmazonSite } from "@/utils/enumUtils"
const getOption = async () => {
  let keys = ["Base.BaseAsinList.ActivityStatusEnum", "Base.BaseAsinList.StatusEnum"]
  const data = await getEnum(keys)
  keys.forEach((key) => {
    originOption.value[key] = data[key]
  })
  originOption.value.amazonSite = (await getAmazonSite()).map((v) => ({ label: v.label, value: v.label }))
}
const title = ref("")

const formData = ref({})
const open = (type, form = {}) => {
  formData.value = form
  modelValue.value = true

  setTimeout(() => {
    let columns = [...tableOptions.columns]
    if (type == "asin") {
      title.value = "选择Asin店铺"
      columns.unshift({ type: "radio", title: "", fixed: "left", width: 60 })
      tableRef?.value.resetForm()
      fieldList.value.map((v) => {
        v.disabled = false
      })
    } else {
      title.value = "选择跟卖店铺"
      columns.unshift({ type: "checkbox", fixed: "left", width: 60 })
      fieldList.value.map((v) => {
        if (["site_code", "asin", "userRange"].includes(v.field)) {
          v.disabled = true
        }
      })

      tableRef?.value.setForm({
        site_code: form.base_asin_list.site_code,
        asin: form.base_asin_list.asin,
        userRange: { type: "operator_user", value: [form.base_asin_list.operator_user] },
      })
    }

    setTimeout(() => {
      nextTick(() => {
        tableRef.value.$table.loadColumn(columns)
        tableRef.value.$table.setAllCheckboxRow()
        tableRef.value.query()
      })
    }, 100)

    if (!originOption.value["Base.BaseAsinList.ActivityStatusEnum"]) {
      getOption()
    }
  }, 100)
}
const initForm = (form) => {
  let keys = ["sku", "custom_sku", "asin"]
  keys.forEach((key) => {
    form[key] = form[key]?.split("\n")?.filter((v) => !!v?.trim())
    form[key] = form[key]?.map((v) => v?.trim())
  })
  return form
}
defineExpose({
  open,
})
</script>
<style lang="scss" scoped></style>
